const router = require('koa-router')();
const registerDestination = require('../app/mws/subscriptions/RegisterDestination');
const createSubscription = require('../app/mws/subscriptions/CreateSubscription');

router.prefix('/api/v1/subscriptions');

router.get('/', function (ctx, next) {
  ctx.body = 'this is a subscriptions response!'
});
/*  使用Policy generator生成的，其中arn:aws:iam::437568002678:root是从MWS Scratchpad调用SendTestNotification会用到
{
  "Version": "2012-10-17",
  "Id": "Policy1602420301985",
  "Statement": [
    {
      "Sid": "Stmt1602420296359",
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "arn:aws:iam::437568002678:root",
          "arn:aws:iam::599885534814:root"
        ]
      },
      "Action": [
        "sqs:ReceiveMessage",
        "sqs:SendMessage"
      ],
      "Resource": "arn:aws:sqs:us-east-2:599885534814:pt-mws-notification"
    }
  ]
}
 */
// https://docs.developer.amazonservices.com/en_UK/subscriptions/Subscriptions_NotificationType.html
// e.g. AnyOfferChanged | FeedProcessingFinished | ReportProcessingFinished
router.post('/create/:marketplaceid/:notificationType', async (ctx, next) => {
  const sellerId = ctx.headers.sellerid;
  const marketplaceid = ctx.params.marketplaceid;
  const notificationType = ctx.params.notificationType;
  console.log(ctx.headers);
  const mwsAuthToken = ctx.headers.mwsauthtoken;
  try {
    let json = await createSubscription.createSubscription(sellerId, mwsAuthToken, marketplaceid, notificationType);
    console.log(json);
    ctx.response.status = 200;
    ctx.response.body = {
      data: json,
    };
  } catch (error) {
    ctx.response.status = 500;
    ctx.response.body = {
      data: error,
    };
  }
});

router.post('/destination/register/:marketplaceid', async (ctx, next) => {
  const sellerId = ctx.headers.sellerid;
  const marketplaceid = ctx.params.marketplaceid;
  console.log(ctx.headers);
  const mwsAuthToken = ctx.headers.mwsauthtoken;
  try {
    let json = await registerDestination.registerDestination(sellerId, mwsAuthToken, marketplaceid);
    console.log(json);
    ctx.response.status = 200;
    ctx.response.body = {
      data: json,
    };
  } catch (error) {
    ctx.response.status = 500;
    ctx.response.body = {
      data: error,
    };
  }
});

module.exports = router;